import Vue from 'vue'
import Router from 'vue-router'
import store from "@/store";
import children from "@/router/children";

Vue.use(Router);

const router = new Router({
  mode: 'history',
  routes: [
    {
      path: '/login',
      name: 'Login',
      component: () => import("@/views/account/loginOauth"),
      meta: {
        role: [],
        title: '登录'
      }
    },
    {
      path: '/page',
      alias: '/',
      children: children,
      redirect: '/page/index',
      component: () => import("@/views/page")
    },
    {
      path: '/*',
      name: 'FirstNotFound',
      component: () => import('@/views/error/NotFound'),
      meta: {
        role: [],
        title: '404'
      }
    }
  ]
});
const permit = ['/login', '/403'];

const originalPush = Router.prototype.push
Router.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

router.beforeEach((to, from, next) => {
  if (permit.indexOf(to.path) === -1) {
    if (store.state.token === undefined) {
      next({path: '/login'})
    } else {
      if (to.meta.role.length > 0) {
        if (store.state.role === undefined) {
          next({path: '/403'})
        }
        if (to.meta.role.indexOf(store.state.role) === -1) {
          next({path: '/403'})
        }
      } else {
        next()
      }
    }
  } else {
    next()
  }
  if (to.meta.title) {
    document.title = to.meta.title
  }
});

export default router
